package codeTop.简单;

/**
 * @author 挚爱之夕
 * @date 2021/9/25 - 09 - 25 - 10:07
 * @Description: codeTop.简单
 * @Version: 1.0
 */
public class _007_字符串相加 {
    public static void main(String[] args) {
        String s1 = "456",s2 = "77";
        String ans = addStrings(s1,s2);
        System.out.println(ans);
    }
    //by myself
    public static String addStrings(String num1, String num2) {
        int len1 = num1.length(),len2 = num2.length();
        int r1 = len1-1,r2=len2-1;
        int digit;
        int rest = 0;
        StringBuilder sb = new StringBuilder();
        if(len1>len2) {
            while(r2>=0){
                int x = num1.charAt(r1--) - '0';
                int y = num2.charAt(r2--) - '0';
                digit = (x + y +rest)%10;
                rest =(x+y+rest-digit)/10;
                sb.append(digit);
            }
            while(r1>=0){
                int t = num1.charAt(r1--) - '0';
                digit = (t + rest)%10;
                rest = (t +rest -digit)/10;
                sb.append(digit);
            }
        }else{
            while(r1>=0){
                int x = num1.charAt(r1--) - '0';
                int y = num2.charAt(r2--) - '0';
                digit = (x + y +rest)%10;
                rest =(x+y+rest-digit)/10;
                sb.append(digit);
            }
            while(r2>=0){
                int t = num2.charAt(r2--) - '0';
                digit = (t + rest)%10;
                rest = (t +rest -digit)/10;
                sb.append(digit);
            }
        }
        if(rest>0)
            sb.append(rest);
        return sb.reverse().toString();
    }
    //摘录
    public static String addStrings1(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuffer ans = new StringBuffer();
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            int result = x + y + add;
            ans.append(result % 10);
            add = result / 10;
            i--;
            j--;
        }
        // 计算完以后的答案需要翻转过来
        ans.reverse();
        return ans.toString();
    }
}
